package com.youlu.campus.service.data.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.data.ActivityUserStatistics;
import com.youlu.campus.service.data.ActivityUserStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;


@Slf4j
@Service
public class ActivityUserStatisticsServiceImpl implements ActivityUserStatisticsService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ActivityUserStatistics findByActivityId(String activityId) {
        Query query = new Query().addCriteria(Criteria.where("activityId").is(activityId));
        ActivityUserStatistics a = mongoTemplate.findOne(query, ActivityUserStatistics.class);
        log.info(":>>> 活动:{} 的报名人员数量:{}", activityId, JSON.toJSON(a));
        return a;
    }

    @Override
    public boolean create(ActivityUserStatistics req) {
        req.setId(null);
        req.setCreatedTime(new Date());
        mongoTemplate.insert(req);
        return true;
    }

    @Override
    public ActivityUserStatistics save(ActivityUserStatistics req) {
        if (StringUtils.isBlank(req.getId())) {
            req.setCreatedTime(new Date());
        } else {
            req.setUpdatedTime(new Date());
        }
        ActivityUserStatistics statistics = mongoTemplate.save(req);
        return statistics;
    }

    @Override
    public void incre(String id, String key, Integer incre) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        Update update = new Update();
        update.inc(key, incre);
        update.set("updatedTime", new Date());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ActivityUserStatistics.class);
        log.info(":>>> 修改活动人数信息:{},结果:{}", id, updateResult.getModifiedCount() > 0 ? true : false);
    }
}
